

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/avatar.gif">
  <link rel="icon" href="/img/avatar.gif">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="马振东">
  <meta name="keywords" content="Java,计算机,数据结构">
  
    <meta name="description" content="channel是一个读写数据的双向通道，通过channel可以将数据读入buffer，也可以将buffer中的数据写入channel，类似于stream，但是比stream更为底层。">
<meta property="og:type" content="article">
<meta property="og:title" content="NIO 基础">
<meta property="og:url" content="https://bolg.plumdong.top/2022/01/15/NIO%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="PlumDong Bolg">
<meta property="og:description" content="channel是一个读写数据的双向通道，通过channel可以将数据读入buffer，也可以将buffer中的数据写入channel，类似于stream，但是比stream更为底层。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f121.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1211.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1212.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1213.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1214.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1215.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1216.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1217.png">
<meta property="og:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f1218.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418151243.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418151605.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418152137.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418154208.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418160106.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162306.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162410.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162750.png">
<meta property="og:image" content="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418163033.png">
<meta property="article:published_time" content="2022-01-14T16:00:00.000Z">
<meta property="article:modified_time" content="2023-03-13T06:57:46.554Z">
<meta property="article:author" content="马振东">
<meta property="article:tag" content="NIO">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://bolg.plumdong.top/myimages/e2f7696577b74c65ad876c29b182f121.png">
  
  
  
  <title>NIO 基础 - PlumDong Bolg</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"bolg.plumdong.top","root":"/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="PlumDong Bolg" type="application/atom+xml">
</head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 60vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>PlumDong Bolg</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="NIO 基础"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-01-15 00:00" pubdate>
          2022年1月15日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          22k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          184 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">NIO 基础</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="一、三大组件"><a href="#一、三大组件" class="headerlink" title="一、三大组件"></a>一、三大组件</h1><h2 id="1、Channel-amp-Buffer"><a href="#1、Channel-amp-Buffer" class="headerlink" title="1、Channel &amp; Buffer"></a>1、<strong>Channel &amp; Buffer</strong></h2><p>channel是一个读写数据的双向通道，通过channel可以将数据读入buffer，也可以将buffer中的数据写入channel，类似于stream，但是比stream更为底层。</p>
<p>常见<strong>Channel</strong> ：</p>
<ul>
<li>FileChannel（文件传输通道）</li>
<li>DatagramChannel（UDP网络传输通道）</li>
<li>SocketChannel（TCP网络传输通道，专用于服务器端）</li>
<li>ServerSocketChannel（TCP网络传输通道）</li>
</ul>
<p>常见<strong>Buffer：</strong></p>
<ul>
<li>ByteBuffer<ul>
<li>MappedByteBuffer</li>
<li>DirectByteBuffer</li>
<li>HeapByteBuffer</li>
</ul>
</li>
<li>ShortBuffer</li>
<li>IntBuffer</li>
<li>LongBuffer</li>
<li>FloatBuffer</li>
<li>DoubleBuffer</li>
<li>CharBuffer</li>
</ul>
<h2 id="2、Selector"><a href="#2、Selector" class="headerlink" title="2、Selector"></a>2、<strong>Selector</strong></h2><p>selector是让一个线程同时管理多个channel，线程可以通过selector获取channel上发生的事件，不会让线程吊死在一个 channel 上，适合连数据量多但流量低的场景。</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f121.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<h1 id="二、ByteBuffer"><a href="#二、ByteBuffer" class="headerlink" title="二、ByteBuffer"></a>二、ByteBuffer</h1><h2 id="1、属性方法"><a href="#1、属性方法" class="headerlink" title="1、属性方法"></a>1、属性方法</h2><p>capacity（缓存容量） position（当前位置） limit （读取限制）</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1211.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<p>写模式下，position是写入位置，limit 等于容量capacity</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1212.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<p>flip 动作发生后，position是读取位置，limit 等于读取限制</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1213.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<p>clear 动作触发后，状态</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1214.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<p>compact 方法，是把未读完的部分向前压缩，然后切换至写模式</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1215.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<p>ByteBuffer常用实现类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestBufferAllocate</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>				System.out.println(ByteBuffer.allocate(<span class="hljs-number">16</span>).getClass());<br><span class="hljs-comment">//        class java.nio.HeapByteBuffer     </span><br><span class="hljs-comment">//        堆内存，读写效率较低，受GC影响</span><br>        System.out.println(ByteBuffer.allocateDirect(<span class="hljs-number">16</span>).getClass());<br><span class="hljs-comment">//        class java.nio.DirectByteBuffer   </span><br><span class="hljs-comment">//        直接内存，读写效率较高（少一次数据拷贝），不受GC影响，分配效率低，可能会导致内存泄漏</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>HeapByteBuffer 和 DirectByteBuffer 关系图：</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1216.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<h2 id="2、粘包与半包"><a href="#2、粘包与半包" class="headerlink" title="2、粘包与半包"></a>2、<strong>粘包与半包</strong></h2><p>网络上有多条数据发送给服务端，数据之间使用 \n 进行分隔但由于某种原因这些数据在接收时，被进行了重新组合，例如原始数据有3条为</p>
<ul>
<li>Hello,world\n</li>
<li>I’m Nyima\n</li>
<li>How are you?\n</li>
</ul>
<p>变成了下面的两个 byteBuffer (粘包，半包)</p>
<ul>
<li>Hello,world\nI’m Nyima\nHo</li>
<li>w are you?\n</li>
</ul>
<h3 id="原因"><a href="#原因" class="headerlink" title="原因:"></a><strong>原因:</strong></h3><p>粘包：发送方在发送数据时，并不是一条一条地发送数据，而是<strong>将数据整合在一起</strong>，当数据达到一定的数量后再一起发送。这就会导致多条信息被放在一个缓冲区中被一起发送出去</p>
<p>半包：接收方的缓冲区的大小是有限的，当接收方的缓冲区满了以后，就需要<strong>将信息截断</strong>，等缓冲区空了以后再继续放入数据。这就会发生一段完整的数据最后被截断的现象</p>
<h3 id="解决办法"><a href="#解决办法" class="headerlink" title="解决办法"></a><strong>解决办法</strong></h3><ul>
<li>通过get(index)方法遍历ByteBuffer，遇到分隔符时进行处理。<strong>注意</strong>：get(index)不会改变position的值<ul>
<li>记录该段数据长度，以便于申请对应大小的缓冲区</li>
<li>将缓冲区的数据通过get()方法写入到target中</li>
</ul>
</li>
<li>调用<strong>compact方法</strong>切换模式，因为缓冲区中可能还有未读的数据</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><br><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> com.plum.netty.nio.ByteBufferUtil.debugAll;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestByteBufferExam</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        ByteBuffer source = ByteBuffer.allocate(<span class="hljs-number">32</span>);<br>        source.put(<span class="hljs-string">&quot;hello,word\nI,m zhangsan\nHo&quot;</span>.getBytes());<br>        split(source);<br>        source.put(<span class="hljs-string">&quot;w are you&quot;</span>.getBytes());<br>        split(source);<br><br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">split</span><span class="hljs-params">(ByteBuffer source)</span> </span>&#123;<br>        source.flip();<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; source.limit(); i++) &#123;<br>            <span class="hljs-keyword">if</span> (source.get(i) == <span class="hljs-string">&#x27;\n&#x27;</span>)&#123;<br>                <span class="hljs-keyword">int</span> length = i + <span class="hljs-number">1</span> - source.position();<br>                ByteBuffer target = ByteBuffer.allocate(length);<br>                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; length; j++) &#123;<br>                    target.put(source.get());<br>                &#125;<br>                debugAll(target);<br>            &#125;<br>        &#125;<br><br>        source.compact();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="三、文件编程"><a href="#三、文件编程" class="headerlink" title="三、文件编程"></a>三、文件编程</h1><h2 id="1、FileChannel"><a href="#1、FileChannel" class="headerlink" title="1、FileChannel"></a>1、<strong>FileChannel</strong></h2><p>FileChannel<strong>只能在阻塞模式下工作</strong>，所以无法搭配Selector</p>
<p><strong>获取</strong></p>
<p>通过 FileInputStream、FileOutputStream 或者 RandomAccessFile 来获取 FileChannel，它们都有 getChannel 方法</p>
<ul>
<li>通过 FileInputStream 获取的 channel <strong>只能读</strong></li>
<li>通过 FileOutputStream 获取的 channel <strong>只能写</strong></li>
<li>通过 RandomAccessFile 是否能读写<strong>根据构造 RandomAccessFile 时的读写模式决定</strong></li>
</ul>
<h2 id="2、两个Channel传输数据"><a href="#2、两个Channel传输数据" class="headerlink" title="2、两个Channel传输数据"></a>2、<strong>两个Channel传输数据</strong></h2><p>使用transferTo方法可以快速、高效地将一个channel中的数据传输到另一个channel中，但<strong>一次只能传输2G的内容</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestChannel</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>&#123;<br>        <span class="hljs-keyword">try</span> (FileInputStream fis = <span class="hljs-keyword">new</span> FileInputStream(<span class="hljs-string">&quot;stu.txt&quot;</span>);<br>             FileOutputStream fos = <span class="hljs-keyword">new</span> FileOutputStream(<span class="hljs-string">&quot;student.txt&quot;</span>);<br>             FileChannel inputChannel = fis.getChannel();<br>             FileChannel outputChannel = fos.getChannel()) &#123;<br>            <span class="hljs-comment">// 参数：inputChannel的起始位置，传输数据的大小，目的channel</span><br>            <span class="hljs-comment">// 返回值为传输的数据的字节数</span><br>            <span class="hljs-comment">// transferTo一次只能传输2G的数据</span><br>            inputChannel.transferTo(<span class="hljs-number">0</span>, inputChannel.size(), outputChannel);<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>当传输的文件<strong>大于2G</strong>时，需要使用以下方法进行多次传输</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestChannel</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span></span>&#123;<br>        <span class="hljs-keyword">try</span> (FileInputStream fis = <span class="hljs-keyword">new</span> FileInputStream(<span class="hljs-string">&quot;stu.txt&quot;</span>);<br>             FileOutputStream fos = <span class="hljs-keyword">new</span> FileOutputStream(<span class="hljs-string">&quot;student.txt&quot;</span>);<br>             FileChannel inputChannel = fis.getChannel();<br>             FileChannel outputChannel = fos.getChannel()) &#123;<br>            <span class="hljs-keyword">long</span> size = inputChannel.size();<br>            <span class="hljs-keyword">long</span> capacity = inputChannel.size();<br>            <span class="hljs-comment">// 分多次传输</span><br>            <span class="hljs-keyword">while</span> (capacity &gt; <span class="hljs-number">0</span>) &#123;<br>                <span class="hljs-comment">// transferTo返回值为传输了的字节数</span><br>                capacity -= inputChannel.transferTo(size-capacity, capacity, outputChannel);<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="五、网络编程"><a href="#五、网络编程" class="headerlink" title="五、网络编程"></a>五、网络编程</h1><h2 id="1、阻塞"><a href="#1、阻塞" class="headerlink" title="1、阻塞"></a>1、阻塞</h2><ul>
<li>阻塞模式下，相关方法都会导致线程暂停<ul>
<li>ServerSocketChannel.accept 会在<strong>没有连接建立时</strong>让线程暂停</li>
<li>SocketChannel.read 会在<strong>通道中没有数据可读时</strong>让线程暂停</li>
<li>阻塞的表现其实就是线程暂停了，暂停期间不会占用 cpu，但线程相当于闲置</li>
</ul>
</li>
<li>单线程下，阻塞方法之间相互影响，几乎不能正常工作，需要多线程支持</li>
<li>但多线程下，有新的问题，体现在以下方面<ul>
<li>32 位 jvm 一个线程 320k，64 位 jvm 一个线程 1024k，如果连接数过多，必然导致 OOM，并且线程太多，反而会因为频繁上下文切换导致性能降低</li>
<li>可以采用线程池技术来减少线程数和线程上下文切换，但治标不治本，如果有很多连接建立，但长时间 inactive，会阻塞线程池中所有线程，因此不适合长连接，只适合短连接</li>
</ul>
</li>
</ul>
<p><strong>服务端代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.util.ArrayList;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Server</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-comment">// 创建缓冲区</span><br>        ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">16</span>);<br>        <span class="hljs-comment">// 获得服务器通道</span><br>        <span class="hljs-keyword">try</span>(ServerSocketChannel server = ServerSocketChannel.open()) &#123;<br>            <span class="hljs-comment">// 为服务器通道绑定端口</span><br>            server.bind(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-number">8080</span>));<br>            <span class="hljs-comment">// 用户存放连接的集合</span><br>            ArrayList&lt;SocketChannel&gt; channels = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>            <span class="hljs-comment">// 循环接收连接</span><br>            <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>) &#123;<br>                System.out.println(<span class="hljs-string">&quot;before connecting...&quot;</span>);<br>                <span class="hljs-comment">// 没有连接时，会阻塞线程</span><br>                SocketChannel socketChannel = server.accept();<br>                System.out.println(<span class="hljs-string">&quot;after connecting...&quot;</span>);<br>                channels.add(socketChannel);<br>                <span class="hljs-comment">// 循环遍历集合中的连接</span><br>                <span class="hljs-keyword">for</span>(SocketChannel channel : channels) &#123;<br>                    System.out.println(<span class="hljs-string">&quot;before reading&quot;</span>);<br>                    <span class="hljs-comment">// 处理通道中的数据</span><br>                    <span class="hljs-comment">// 当通道中没有数据可读时，会阻塞线程</span><br>                    channel.read(buffer);<br>                    buffer.flip();<br>                    ByteBufferUtil.debugRead(buffer);<br>                    buffer.clear();<br>                    System.out.println(<span class="hljs-string">&quot;after reading&quot;</span>);<br>                &#125;<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>客户端代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.nio.charset.Charset;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-keyword">try</span> (SocketChannel socketChannel = SocketChannel.open()) &#123;<br>            <span class="hljs-comment">// 建立连接</span><br>            socketChannel.connect(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-string">&quot;localhost&quot;</span>, <span class="hljs-number">8080</span>));<br>            socketChannel.write(Charset.defaultCharset().encode(<span class="hljs-string">&quot;hello!&quot;</span>));<br>            System.out.println(<span class="hljs-string">&quot;waiting...&quot;</span>);<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="2、非阻塞"><a href="#2、非阻塞" class="headerlink" title="2、非阻塞"></a>2、非阻塞</h2><ul>
<li>可以通过ServerSocketChannel的configureBlocking(<strong>false</strong>)方法将<strong>获得连接设置为非阻塞的</strong>。此时若没有连接，accept会返回null</li>
<li>可以通过SocketChannel的configureBlocking(<strong>false</strong>)方法将从通道中<strong>读取数据设置为非阻塞的</strong>。若此时通道中没有数据可读，read会返回-1</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.util.ArrayList;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Server</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-comment">// 创建缓冲区</span><br>        ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">16</span>);<br>        <span class="hljs-comment">// 获得服务器通道</span><br>        <span class="hljs-keyword">try</span>(ServerSocketChannel server = ServerSocketChannel.open()) &#123;<br>            <span class="hljs-comment">// 为服务器通道绑定端口</span><br>            server.bind(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-number">8080</span>));<br>            <span class="hljs-comment">// 用户存放连接的集合</span><br>            ArrayList&lt;SocketChannel&gt; channels = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>            <span class="hljs-comment">// 循环接收连接</span><br>            <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>) &#123;<br>                <span class="hljs-comment">// 设置为非阻塞模式，没有连接时返回null，不会阻塞线程</span><br>                server.configureBlocking(<span class="hljs-keyword">false</span>);<br>                SocketChannel socketChannel = server.accept();<br>                <span class="hljs-comment">// 通道不为空时才将连接放入到集合中</span><br>                <span class="hljs-keyword">if</span> (socketChannel != <span class="hljs-keyword">null</span>) &#123;<br>                    System.out.println(<span class="hljs-string">&quot;after connecting...&quot;</span>);<br>                    channels.add(socketChannel);<br>                &#125;<br>                <span class="hljs-comment">// 循环遍历集合中的连接</span><br>                <span class="hljs-keyword">for</span>(SocketChannel channel : channels) &#123;<br>                    <span class="hljs-comment">// 处理通道中的数据</span><br>                    <span class="hljs-comment">// 设置为非阻塞模式，若通道中没有数据，会返回0，不会阻塞线程</span><br>                    channel.configureBlocking(<span class="hljs-keyword">false</span>);<br>                    <span class="hljs-keyword">int</span> read = channel.read(buffer);<br>                    <span class="hljs-keyword">if</span>(read &gt; <span class="hljs-number">0</span>) &#123;<br>                        buffer.flip();<br>                        ByteBufferUtil.debugRead(buffer);<br>                        buffer.clear();<br>                        System.out.println(<span class="hljs-string">&quot;after reading&quot;</span>);<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="3、Selector"><a href="#3、Selector" class="headerlink" title="3、Selector"></a>3、<strong>Selector</strong></h2><p><strong>多路复用</strong></p>
<p>单线程可以配合 Selector 完成对多个 Channel 可读写事件的监控，这称之为多路复用</p>
<ul>
<li><strong>多路复用仅针对网络 IO</strong>，普通文件 IO 无法利用多路复用</li>
<li>如果不用 Selector 的非阻塞模式，线程大部分时间都在做无用功，而 Selector 能够保证<ul>
<li>有可连接事件时才去连接</li>
<li>有可读事件才去读取</li>
<li>有可写事件才去写入</li>
</ul>
</li>
<li>限于网络传输能力，Channel 未必时时可写，一旦 Channel 可写，会触发 Selector 的可写事件</li>
</ul>
<p><strong>selector多路复用步骤：</strong></p>
<ul>
<li>通道设置为非阻塞模式并注册到选择器中，并设置感兴趣的事件</li>
<li>channel 必须工作在非阻塞模式</li>
<li>FileChannel 没有非阻塞模式，因此不能配合 selector 一起使用</li>
<li>绑定的<strong>事件类型</strong>可以有<ul>
<li>connect - 客户端连接成功时触发</li>
<li>accept - 服务器端成功接受连接时触发</li>
<li>read - 数据可读入时触发，有因为接收能力弱，数据暂不能读入的情况</li>
<li>write - 数据可写出时触发，有因为发送能力弱，数据暂不能写出的情况</li>
</ul>
  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 通道必须设置为非阻塞模式</span><br>server.configureBlocking(<span class="hljs-keyword">false</span>);<br><span class="hljs-comment">// 将通道注册到选择器中，并设置感兴趣的实践</span><br>server.register(selector, SelectionKey.OP_ACCEPT);<br></code></pre></td></tr></table></figure>
</li>
<li>Selector监听事件：获取就绪通道个数，若没有通道就绪，线程阻塞  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//阻塞直至有绑定事件发生</span><br><span class="hljs-keyword">int</span> count = selector.select();<br><span class="hljs-comment">//阻塞直到绑定事件发生，或是超时（时间单位为 ms）</span><br><span class="hljs-keyword">int</span> count = selector.select(<span class="hljs-keyword">long</span> timeout);<br><span class="hljs-comment">//不会阻塞，也就是不管有没有事件，立刻返回，自己根据返回值检查是否有事件</span><br><span class="hljs-keyword">int</span> count = selector.selectNow();<br></code></pre></td></tr></table></figure>
</li>
<li><strong>事件发生后，要么处理，要么取消（cancel），不能什么都不做，否则下次该事件仍会触发，这是因为 nio 底层使用的是水平触发。</strong></li>
</ul>
<p><strong>多路复用服务端代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.SelectionKey;<br><span class="hljs-keyword">import</span> java.nio.channels.Selector;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.util.Iterator;<br><span class="hljs-keyword">import</span> java.util.Set;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SelectServer</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">16</span>);<br>        <span class="hljs-comment">// 获得服务器通道</span><br>        <span class="hljs-keyword">try</span>(ServerSocketChannel server = ServerSocketChannel.open()) &#123;<br>            server.bind(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-number">8080</span>));<br>            <span class="hljs-comment">// 创建选择器</span><br>            Selector selector = Selector.open();<br><br>            <span class="hljs-comment">// 通道必须设置为非阻塞模式</span><br>            server.configureBlocking(<span class="hljs-keyword">false</span>);<br>            <span class="hljs-comment">// 将通道注册到选择器中，并设置感兴趣的事件</span><br>            server.register(selector, SelectionKey.OP_ACCEPT);<br>            <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>) &#123;<br>                <span class="hljs-comment">// 若没有事件就绪，线程会被阻塞，反之不会被阻塞。从而避免了CPU空转</span><br>                <span class="hljs-comment">// 返回值为就绪的事件个数</span><br>                <span class="hljs-keyword">int</span> ready = selector.select();<br>                System.out.println(<span class="hljs-string">&quot;selector ready counts : &quot;</span> + ready);<br><br>                <span class="hljs-comment">// 获取所有事件</span><br>                Set&lt;SelectionKey&gt; selectionKeys = selector.selectedKeys();<br><br>                <span class="hljs-comment">// 使用迭代器遍历事件</span><br>                Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();<br>                <span class="hljs-keyword">while</span> (iterator.hasNext()) &#123;<br>                    SelectionKey key = iterator.next();<br><br>                    <span class="hljs-comment">// 判断key的类型</span><br>                    <span class="hljs-keyword">if</span>(key.isAcceptable()) &#123;<br>                        <span class="hljs-comment">// 获得key对应的channel</span><br>                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();<br>                        System.out.println(<span class="hljs-string">&quot;before accepting...&quot;</span>);<br><br>                        <span class="hljs-comment">// 获取连接并处理，而且是必须处理，否则需要取消</span><br>                        SocketChannel socketChannel = channel.accept();<br>                        System.out.println(<span class="hljs-string">&quot;after accepting...&quot;</span>);<br><br>                        <span class="hljs-comment">// 处理完毕后移除</span><br>                        iterator.remove();<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="4、Read事件"><a href="#4、Read事件" class="headerlink" title="4、Read事件"></a>4、Read事件</h2><p>在Accept事件中，若有客户端与服务器端建立了连接，需要将其对应的SocketChannel设置为非阻塞，并注册到选择其中Selector 中 关联read事件。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.SelectionKey;<br><span class="hljs-keyword">import</span> java.nio.channels.Selector;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.util.Iterator;<br><span class="hljs-keyword">import</span> java.util.Set;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SelectServer</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">16</span>);<br>        <span class="hljs-comment">// 获得服务器通道</span><br>        <span class="hljs-keyword">try</span>(ServerSocketChannel server = ServerSocketChannel.open()) &#123;<br>            server.bind(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-number">8080</span>));<br>            <span class="hljs-comment">// 创建选择器</span><br>            Selector selector = Selector.open();<br>            <span class="hljs-comment">// 通道必须设置为非阻塞模式</span><br>            server.configureBlocking(<span class="hljs-keyword">false</span>);<br>            <span class="hljs-comment">// 将通道注册到选择器中，并设置感兴趣的实践</span><br>            server.register(selector, SelectionKey.OP_ACCEPT);<br>            <span class="hljs-comment">// 为serverKey设置感兴趣的事件</span><br>            <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>) &#123;<br>                <span class="hljs-comment">// 若没有事件就绪，线程会被阻塞，反之不会被阻塞。从而避免了CPU空转</span><br>                <span class="hljs-comment">// 返回值为就绪的事件个数</span><br>                <span class="hljs-keyword">int</span> ready = selector.select();<br>                System.out.println(<span class="hljs-string">&quot;selector ready counts : &quot;</span> + ready);<br>                <span class="hljs-comment">// 获取所有事件</span><br>                Set&lt;SelectionKey&gt; selectionKeys = selector.selectedKeys();<br>                <span class="hljs-comment">// 使用迭代器遍历事件</span><br>                Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();<br>                <span class="hljs-keyword">while</span> (iterator.hasNext()) &#123;<br>                    SelectionKey key = iterator.next();<br>                    <span class="hljs-comment">// 判断key的类型</span><br>                    <span class="hljs-keyword">if</span>(key.isAcceptable()) &#123;<br>                        <span class="hljs-comment">// 获得key对应的channel</span><br>                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();<br>                        System.out.println(<span class="hljs-string">&quot;before accepting...&quot;</span>);<br>                        <span class="hljs-comment">// 获取连接</span><br>                        SocketChannel socketChannel = channel.accept();<br>                        System.out.println(<span class="hljs-string">&quot;after accepting...&quot;</span>);<br>                        <span class="hljs-comment">// 设置为非阻塞模式，同时将连接的通道也注册到选择其中</span><br>                        socketChannel.configureBlocking(<span class="hljs-keyword">false</span>);<br>                        socketChannel.register(selector, SelectionKey.OP_READ);<br>                        <span class="hljs-comment">// 处理完毕后移除</span><br>                        iterator.remove();<br>                    &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isReadable()) &#123;<br>                        <span class="hljs-keyword">try</span> &#123;<br>                            SocketChannel channel = (SocketChannel) key.channel();<br>                            System.out.println(<span class="hljs-string">&quot;before reading...&quot;</span>);<br>                            <span class="hljs-keyword">int</span> read = channel.read(buffer);<br>                            System.out.println(<span class="hljs-string">&quot;after reading...&quot;</span>);<br>                            <span class="hljs-keyword">if</span> (read == -<span class="hljs-number">1</span>)&#123;<br>                                key.cancel();<br>                            &#125;<span class="hljs-keyword">else</span> &#123;<br>                                buffer.flip();<br>                                ByteBufferUtil.debugRead(buffer);<br>                            &#125;<br>                        &#125;<span class="hljs-keyword">catch</span> (IOException e)&#123;<br>                            e.printStackTrace();<br>                            key.cancel();   <span class="hljs-comment">//客户端断开后，channel.read 会抛出 IOException ，并取消事件</span><br>                        &#125;<span class="hljs-keyword">finally</span> &#123;<br>                            buffer.clear();<br>                        &#125;<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>处理消息的边界</strong></p>
<p>客户端发送中文字符 “你好”，共6个字节，而服务端byteBuffer大小设置为4，不足以一次性接收所有信息，则会出现乱码情况。</p>
<p><img src="/myimages/e2f7696577b74c65ad876c29b182f1217.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></p>
<p>解决思路：</p>
<ul>
<li><strong>固定消息长度</strong>，数据包大小一样，服务器按预定长度读取，当发送的数据较少时，需要将数据进行填充，直到长度与消息规定长度一致。缺点是浪费带宽</li>
<li>另一种思路是按分隔符拆分，缺点是效率低，需要一个一个字符地去匹配分隔符</li>
<li><strong>TLV 格式，即 Type 类型、Length 长度、Value 数据</strong>（也就是在消息开头<strong>用一些空间存放后面数据的长度</strong>），如HTTP请求头中的Content-Type与<strong>Content-Length</strong>。类型和长度已知的情况下，就可以方便获取消息大小，分配合适的 buffer，缺点是 buffer 需要提前分配，如果内容过大，则影响 server 吞吐量<ul>
<li>Http 1.1 是 TLV 格式</li>
<li>Http 2.0 是 LTV 格式</li>
</ul>
  <img src="/myimages/e2f7696577b74c65ad876c29b182f1218.png" srcset="/img/loading.gif" lazyload alt="NIO基础"></li>
</ul>
<h2 id="5、Write事件"><a href="#5、Write事件" class="headerlink" title="5、Write事件"></a>5、Write事件</h2><p>服务器通过Buffer向通道中写入数据时，<strong>如果通道容量小于Buffer中的数据大小，便需要分多次写入：</strong></p>
<ul>
<li>执行一次写操作，向将buffer中的内容写入到SocketChannel中，然后判断Buffer中是否还有数据</li>
<li>若Buffer中还有数据，则需要将SockerChannel注册到Seletor中，并关注写事件，同时将未写完的Buffer作为附件一起放入到SelectionKey中</li>
<li>添加写事件的相关操作key.isWritable()，对Buffer再次进行写操作。每次写后需要判断Buffer中是否还有数据（是否写完）。<strong>若写完，需要移除SelecionKey中的Buffer附件，避免其占用过多内存，同时还需移除对写事件的关注。</strong></li>
</ul>
<p><strong>服务端发送数据代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.SelectionKey;<br><span class="hljs-keyword">import</span> java.nio.channels.Selector;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.nio.charset.Charset;<br><span class="hljs-keyword">import</span> java.util.Iterator;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WriteServer</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        ServerSocketChannel ssc = ServerSocketChannel.open();<br>        ssc.configureBlocking(<span class="hljs-keyword">false</span>);<br>        Selector selector = Selector.open();<br>        ssc.register(selector, SelectionKey.OP_ACCEPT);<br>        ssc.bind(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-number">8080</span>));<br><br>        <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>)&#123;<br>            selector.select();<br>            Iterator&lt;SelectionKey&gt; iterator = selector.selectedKeys().iterator();<br>            <span class="hljs-keyword">while</span> (iterator.hasNext())&#123;<br>                SelectionKey key = iterator.next();<br>                iterator.remove();<br>                <span class="hljs-keyword">if</span> (key.isAcceptable())&#123;<br>                    SocketChannel sc = ssc.accept();<br>                    sc.configureBlocking(<span class="hljs-keyword">false</span>);<br>                    SelectionKey sckey = sc.register(selector, <span class="hljs-number">0</span>, <span class="hljs-keyword">null</span>);<br>                    StringBuffer sb = <span class="hljs-keyword">new</span> StringBuffer();<br>                    <span class="hljs-comment">// 1. 向客户端发送大量数据</span><br>                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">30000000</span>; i++) &#123;<br>                        sb.append(<span class="hljs-string">&quot;a&quot;</span>);<br>                    &#125;<br>                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());<br>                    <span class="hljs-comment">// 2. 返回值代表实际写入的字节数</span><br>                    <span class="hljs-keyword">int</span> write = sc.write(buffer);<br>                    System.out.println(write);<br>                    <span class="hljs-comment">// 3. 判断是否有剩余内容</span><br>                    <span class="hljs-keyword">if</span> (buffer.hasRemaining())&#123;<br>                        <span class="hljs-comment">// 4. 关注可写事件</span><br>                        sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);<br>                        <span class="hljs-comment">// 5. 把未写完的数据挂到 sckey上</span><br>                        sckey.attach(buffer);<br>                    &#125;<br>                &#125;<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isWritable())&#123;<br>                    ByteBuffer buffer = (ByteBuffer) key.attachment();<br>                    SocketChannel sc = (SocketChannel)key.channel();<br>                    <span class="hljs-keyword">int</span> write = sc.write(buffer);<br>                    System.out.println(write);<br>                    <span class="hljs-comment">//清理操作</span><br>                    <span class="hljs-keyword">if</span> (!buffer.hasRemaining())&#123;<br>                        key.attach(<span class="hljs-keyword">null</span>);   <span class="hljs-comment">//清楚 buffer</span><br>                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE); <span class="hljs-comment">//注销可写事件</span><br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>客户端接收数据代码：</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReadClient</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        SocketChannel sc = SocketChannel.open();<br>        sc.connect(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-string">&quot;localhost&quot;</span>, <span class="hljs-number">8080</span>));<br><br>        <span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>;<br><br>        <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>)&#123;<br>            ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>);<br>            count += sc.read(buffer);<br>            System.out.println(count);<br>            buffer.clear();<br>        &#125;<br><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="6、多线程优化"><a href="#6、多线程优化" class="headerlink" title="6、多线程优化"></a>6、多线程优化</h2><ul>
<li>创建一个负责处理Accept事件的Boss线程，与多个负责处理Read事件的Worker线程</li>
<li>Boss线程执行的操作<ul>
<li>接受并处理Accepet事件，当Accept事件发生后，调用Worker的register(SocketChannel socket)方法，让Worker去处理Read事件，其中需要根据标识robin去判断将任务分配给哪个Worker</li>
<li>register(SocketChannel socket)方法会通过同步队列完成Boss线程与Worker线程之间的通信，让SocketChannel的注册任务被Worker线程执行。添加任务后需要调用selector.wakeup()来唤醒被阻塞的Selector</li>
</ul>
</li>
<li>Worker线程执行的操作<ul>
<li>从同步队列中获取注册任务，并处理Read事件</li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.SelectionKey;<br><span class="hljs-keyword">import</span> java.nio.channels.Selector;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.util.Iterator;<br><span class="hljs-keyword">import</span> java.util.Set;<br><span class="hljs-keyword">import</span> java.util.concurrent.ConcurrentLinkedQueue;<br><span class="hljs-keyword">import</span> java.util.concurrent.atomic.AtomicInteger;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MultiThreadServer</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-keyword">try</span> (ServerSocketChannel server = ServerSocketChannel.open()) &#123;<br>            <span class="hljs-comment">// 当前线程为Boss线程</span><br>            Thread.currentThread().setName(<span class="hljs-string">&quot;Boss&quot;</span>);<br>            server.bind(<span class="hljs-keyword">new</span> InetSocketAddress(<span class="hljs-number">8080</span>));<br>            <span class="hljs-comment">// 负责轮询Accept事件的Selector</span><br>            Selector boss = Selector.open();<br>            server.configureBlocking(<span class="hljs-keyword">false</span>);<br>            server.register(boss, SelectionKey.OP_ACCEPT);<br>            <span class="hljs-comment">// 创建固定数量的Worker</span><br>            Worker[] workers = <span class="hljs-keyword">new</span> Worker[<span class="hljs-number">4</span>];<br>            <span class="hljs-comment">// 用于负载均衡的原子整数</span><br>            AtomicInteger robin = <span class="hljs-keyword">new</span> AtomicInteger(<span class="hljs-number">0</span>);<br>            <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; workers.length; i++) &#123;<br>                workers[i] = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">&quot;worker-&quot;</span>+i);<br>            &#125;<br>            <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>) &#123;<br>                boss.select();<br>                Set&lt;SelectionKey&gt; selectionKeys = boss.selectedKeys();<br>                Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();<br>                <span class="hljs-keyword">while</span> (iterator.hasNext()) &#123;<br>                    SelectionKey key = iterator.next();<br>                    iterator.remove();<br>                    <span class="hljs-comment">// BossSelector负责Accept事件</span><br>                    <span class="hljs-keyword">if</span> (key.isAcceptable()) &#123;<br>                        <span class="hljs-comment">// 建立连接</span><br>                        SocketChannel socket = server.accept();<br>                        System.out.println(<span class="hljs-string">&quot;connected...&quot;</span>);<br>                        socket.configureBlocking(<span class="hljs-keyword">false</span>);<br>                        <span class="hljs-comment">// socket注册到Worker的Selector中</span><br>                        System.out.println(<span class="hljs-string">&quot;before read...&quot;</span>);<br>                        <span class="hljs-comment">// 负载均衡，轮询分配Worker</span><br>                        workers[robin.getAndIncrement()% workers.length].register(socket);<br>                        System.out.println(<span class="hljs-string">&quot;after read...&quot;</span>);<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br><br>    <br>    <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Worker</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>&#123;<br>        <span class="hljs-keyword">private</span> Thread thread;<br>        <span class="hljs-keyword">private</span> <span class="hljs-keyword">volatile</span> Selector selector;<br>        <span class="hljs-keyword">private</span> String name;<br>        <span class="hljs-keyword">private</span> <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">boolean</span> started = <span class="hljs-keyword">false</span>;<br>        <span class="hljs-comment">/**</span><br><span class="hljs-comment">         * 同步队列，用于Boss线程与Worker线程之间的通信</span><br><span class="hljs-comment">         */</span><br>        <span class="hljs-keyword">private</span> ConcurrentLinkedQueue&lt;Runnable&gt; queue;<br><br>        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Worker</span><span class="hljs-params">(String name)</span> </span>&#123;<br>            <span class="hljs-keyword">this</span>.name = name;<br>        &#125;<br><br>        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">register</span><span class="hljs-params">(<span class="hljs-keyword">final</span> SocketChannel socket)</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>            <span class="hljs-comment">// 只启动一次</span><br>            <span class="hljs-keyword">if</span> (!started) &#123;<br>                thread = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">this</span>, name);<br>                selector = Selector.open();<br>                queue = <span class="hljs-keyword">new</span> ConcurrentLinkedQueue&lt;&gt;();<br>                thread.start();<br>                started = <span class="hljs-keyword">true</span>;<br>            &#125;<br><br>            <span class="hljs-comment">// 向同步队列中添加SocketChannel的注册事件</span><br>            <span class="hljs-comment">// 在Worker线程中执行注册事件</span><br>            queue.add(() -&gt; &#123;<br>                    <span class="hljs-keyword">try</span> &#123;<br>                        socket.register(selector, SelectionKey.OP_READ);<br>                    &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>                        e.printStackTrace();<br>                    &#125;<br>                &#125;);<br>            <span class="hljs-comment">// 唤醒被阻塞的Selector</span><br>            <span class="hljs-comment">// select类似LockSupport中的park，wakeup的原理类似LockSupport中的unpark</span><br>            selector.wakeup();<br>        &#125;<br><br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;<br>            <span class="hljs-keyword">while</span> (<span class="hljs-keyword">true</span>) &#123;<br>                <span class="hljs-keyword">try</span> &#123;<br>                    selector.select();<br>                    <span class="hljs-comment">// 通过同步队列获得任务并运行</span><br>                    Runnable task = queue.poll();<br>                    <span class="hljs-keyword">if</span> (task != <span class="hljs-keyword">null</span>) &#123;<br>                        <span class="hljs-comment">// 获得任务，执行注册操作</span><br>                        task.run();<br>                    &#125;<br>                    Set&lt;SelectionKey&gt; selectionKeys = selector.selectedKeys();<br>                    Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();<br>                    <span class="hljs-keyword">while</span>(iterator.hasNext()) &#123;<br>                        SelectionKey key = iterator.next();<br>                        iterator.remove();<br>                        <span class="hljs-comment">// Worker只负责Read事件</span><br>                        <span class="hljs-keyword">if</span> (key.isReadable()) &#123;<br>                            <span class="hljs-comment">// 简化处理，省略细节</span><br>                            SocketChannel socket = (SocketChannel) key.channel();<br>                            ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">16</span>);<br>                            socket.read(buffer);<br>                            buffer.flip();<br>                            ByteBufferUtil.debugAll(buffer);<br>                        &#125;<br>                    &#125;<br>                &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>                    e.printStackTrace();<br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="六、NIO与BIO"><a href="#六、NIO与BIO" class="headerlink" title="六、NIO与BIO"></a>六、<strong>NIO与BIO</strong></h1><h2 id="1、Stream与Channel"><a href="#1、Stream与Channel" class="headerlink" title="1、Stream与Channel"></a><strong>1、Stream与Channel</strong></h2><ul>
<li>stream 不会自动缓冲数据，channel 会利用系统提供的发送缓冲区、接收缓冲区（更为底层）</li>
<li>stream 仅支持阻塞 API，channel 同时支持阻塞、非阻塞 API，<strong>网络 channel 可配合 selector 实现多路复用</strong></li>
<li>二者<strong>均为全双工</strong>，即读写可以同时进行（虽然Stream是单向流动的，但是它也是全双工的）</li>
</ul>
<h2 id="2、IO模型"><a href="#2、IO模型" class="headerlink" title="2、IO模型"></a><strong>2、IO模型</strong></h2><ul>
<li><strong>同步</strong>：线程自己去获取结果（一个线程）<ul>
<li>例如：线程调用一个方法后，需要等待方法返回结果</li>
</ul>
</li>
<li><strong>异步</strong>：线程自己不去获取结果，而是由其它线程返回结果（至少两个线程）<ul>
<li>例如：线程A调用一个方法后，继续向下运行，运行结果由线程B返回</li>
</ul>
</li>
</ul>
<p>当调用一次 channel.<strong>read</strong> 或 stream.<strong>read</strong> 后，会由用户态切换至操作系统内核态来完成真正数据读取，而读取又分为两个阶段，分别为：</p>
<ul>
<li>等待数据阶段</li>
<li>复制数据阶段</li>
</ul>
<p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418151243.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418151243.png"></p>
<p><strong>根据UNIX 网络编程 - 卷 I，IO模型主要有以下几种</strong></p>
<h3 id="阻塞IO"><a href="#阻塞IO" class="headerlink" title="阻塞IO"></a><strong>阻塞IO</strong></h3><p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418151605.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418151605.png"></p>
<ul>
<li>用户线程进行read操作时，<strong>需要等待操作系统执行实际的read操作</strong>，此期间用户线程是被阻塞的，无法执行其他操作</li>
</ul>
<h3 id="非阻塞IO"><a href="#非阻塞IO" class="headerlink" title="非阻塞IO"></a><strong>非阻塞IO</strong></h3><p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418152137.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418152137.png"></p>
<ul>
<li>用户线程<strong>在一个循环中一直调用read方法</strong>，若内核空间中还没有数据可读，立即返回，<strong>只是在等待阶段非阻塞。</strong></li>
<li>用户线程发现内核空间中有数据后，等待内核空间执行复制数据，待复制结束后返回结果</li>
</ul>
<h3 id="多路复用"><a href="#多路复用" class="headerlink" title="多路复用"></a><strong>多路复用</strong></h3><p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418154208.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418154208.png"></p>
<p><strong>Java中通过Selector实现多路复用</strong></p>
<ul>
<li>当没有事件时，调用select方法会被阻塞住</li>
<li>一旦有一个或多个事件发生后，就会处理对应的事件，从而实现多路复用</li>
</ul>
<p><strong>多路复用与阻塞IO的区别</strong></p>
<ul>
<li>阻塞IO模式下，<strong>若线程因accept事件被阻塞，发生read事件后，仍需等待accept事件执行完成后</strong>，才能去处理read事件</li>
<li>多路复用模式下，一个事件发生后，若另一个事件处于阻塞状态，不会影响该事件的执行</li>
</ul>
<h3 id="异步IO"><a href="#异步IO" class="headerlink" title="异步IO"></a><strong>异步IO</strong></h3><p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418160106.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418160106.png"></p>
<ul>
<li>线程1调用方法后理解返回，<strong>不会被阻塞也不需要立即获取结果</strong></li>
<li>当方法的运行结果出来以后，由线程2将结果返回给线程1</li>
</ul>
<h2 id="3、零拷贝"><a href="#3、零拷贝" class="headerlink" title="3、零拷贝"></a><strong>3、零拷贝</strong></h2><p><strong>零拷贝指的是数据无需拷贝到 JVM 内存中</strong>，同时具有以下三个优点</p>
<ul>
<li>更少的用户态与内核态的切换</li>
<li>不利用 cpu 计算，减少 cpu 缓存伪共享</li>
<li>零拷贝适合小文件传输</li>
</ul>
<h3 id="传统-IO-问题"><a href="#传统-IO-问题" class="headerlink" title="传统 IO 问题"></a><strong>传统 IO 问题</strong></h3><p>传统的 IO 将一个文件通过 socket 写出</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java">File f = <span class="hljs-keyword">new</span> File(<span class="hljs-string">&quot;helloword/data.txt&quot;</span>);<br>RandomAccessFile file = <span class="hljs-keyword">new</span> RandomAccessFile(file, <span class="hljs-string">&quot;r&quot;</span>);<br><br><span class="hljs-keyword">byte</span>[] buf = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[(<span class="hljs-keyword">int</span>)f.length()];<br>file.read(buf);<br><br>Socket socket = ...;<br>socket.getOutputStream().write(buf);Copy<br></code></pre></td></tr></table></figure>

<p><strong>内部工作流如下</strong></p>
<p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162306.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162306.png"></p>
<ul>
<li>Java 本身并不具备 IO 读写能力，因此 read 方法调用后，要从 Java 程序的<strong>用户态切换至内核态</strong>，去调用操作系统（Kernel）的读能力，将数据读入<strong>内核缓冲区</strong>。这期间用户线程阻塞，操作系统使用 DMA（Direct Memory Access）来实现文件读，其间也不会使用 CPU  <code>DMA 也可以理解为硬件单元，用来解放 cpu 完成文件 IO</code></li>
<li>从<strong>内核态</strong>切换回<strong>用户态</strong>，将数据从<strong>内核缓冲区</strong>读入<strong>用户缓冲区</strong>（即 byte[] buf），这期间 <strong>CPU 会参与拷贝</strong>，无法利用 DMA</li>
<li>调用 write 方法，这时将数据从<strong>用户缓冲区</strong>（byte[] buf）写入 <strong>socket 缓冲区，CPU 会参与拷贝</strong></li>
<li>接下来要向网卡写数据，这项能力 Java 又不具备，因此又得从<strong>用户态</strong>切换至<strong>内核态</strong>，调用操作系统的写能力，使用 DMA 将 <strong>socket 缓冲区</strong>的数据写入网卡，不会使用 CPU</li>
</ul>
<p>可以看到中间环节较多，java 的 IO 实际不是物理设备级别的读写，而是缓存的复制，底层的真正读写是操作系统来完成的</p>
<ul>
<li>用户态与内核态的切换发生了 3 次，这个操作比较重量级</li>
<li>数据拷贝了共 4 次</li>
</ul>
<h3 id="NIO-优化"><a href="#NIO-优化" class="headerlink" title="NIO 优化"></a><strong>NIO 优化</strong></h3><p>通过 <strong>DirectByteBuf</strong></p>
<ul>
<li>ByteBuffer.allocate(10)<ul>
<li>底层对应 HeapByteBuffer，使用的还是 Java 内存</li>
</ul>
</li>
<li>ByteBuffer.<strong>allocateDirect</strong>(10)<ul>
<li>底层对应DirectByteBuffer，<strong>使用的是操作系统内存</strong></li>
</ul>
</li>
</ul>
<p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162410.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162410.png"></p>
<p>大部分步骤与优化前相同，唯有一点：<strong>Java 可以使用 DirectByteBuffer 将堆外内存映射到 JVM 内存中来直接访问使用</strong></p>
<ul>
<li>这块内存不受 JVM 垃圾回收的影响，因此内存地址固定，有助于 IO 读写</li>
<li>Java 中的 DirectByteBuf 对象仅维护了此内存的虚引用，内存回收分成两步<ul>
<li>DirectByteBuffer 对象被垃圾回收，将虚引用加入引用队列<ul>
<li>当引用的对象ByteBuffer被垃圾回收以后，虚引用对象Cleaner就会被放入引用队列中，然后调用Cleaner的clean方法来释放直接内存</li>
<li>DirectByteBuffer 的释放底层调用的是 Unsafe 的 freeMemory 方法</li>
</ul>
</li>
<li>通过专门线程访问引用队列，根据虚引用释放堆外内存</li>
</ul>
</li>
<li><strong>减少了一次数据拷贝，用户态与内核态的切换次数没有减少</strong></li>
</ul>
<h3 id="进一步优化1"><a href="#进一步优化1" class="headerlink" title="进一步优化1"></a><strong>进一步优化1</strong></h3><p><strong>以下两种方式都是零拷贝</strong>，即无需将数据拷贝到用户缓冲区中（JVM内存中）</p>
<p>底层采用了 <strong>linux 2.1</strong> 后提供的 <strong>sendFile</strong> 方法，Java 中对应着两个 channel 调用 <strong>transferTo/transferFrom</strong> 方法拷贝数据</p>
<p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162750.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418162750.png"></p>
<ul>
<li>Java 调用 transferTo 方法后，要从 Java 程序的<strong>用户态</strong>切换至<strong>内核态</strong>，使用 DMA将数据读入<strong>内核缓冲区</strong>，不会使用 CPU</li>
<li>数据从<strong>内核缓冲区</strong>传输到 <strong>socket 缓冲区</strong>，CPU 会参与拷贝</li>
<li>最后使用 DMA 将 <strong>socket 缓冲区</strong>的数据写入网卡，不会使用 CPU</li>
</ul>
<p>这种方法下</p>
<ul>
<li>只发生了1次用户态与内核态的切换</li>
<li>数据拷贝了 3 次</li>
</ul>
<h3 id="进一步优化2"><a href="#进一步优化2" class="headerlink" title="进一步优化2"></a><strong>进一步优化2</strong></h3><p><strong>linux 2.4</strong> 对上述方法再次进行了优化</p>
<p><img src="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418163033.png" srcset="/img/loading.gif" lazyload alt="https://nyimapicture.oss-cn-beijing.aliyuncs.com/img/20210418163033.png"></p>
<ul>
<li>Java 调用 transferTo 方法后，要从 Java 程序的<strong>用户态</strong>切换至<strong>内核态</strong>，使用 DMA将数据读入<strong>内核缓冲区</strong>，不会使用 CPU</li>
<li>只会将一些 offset 和 length 信息拷入 <strong>socket 缓冲区</strong>，几乎无消耗</li>
<li>使用 DMA 将 <strong>内核缓冲区</strong>的数据写入网卡，不会使用 CPU</li>
</ul>
<p><strong>整个过程仅只发生了1次用户态与内核态的切换，数据拷贝了 2 次</strong></p>
<h2 id="4、AIO"><a href="#4、AIO" class="headerlink" title="4、AIO"></a><strong>4、AIO</strong></h2><p>AIO 用来解决数据复制阶段的阻塞问题</p>
<ul>
<li>同步意味着，在进行读写操作时，线程需要等待结果，还是相当于闲置</li>
<li>异步意味着，在进行读写操作时，线程不必等待结果，而是将来由操作系统来通过回调方式由另外的线程来获得结果</li>
<li>异步模型需要底层操作系统（Kernel）提供支持</li>
<li>Windows 系统通过 IOCP <strong>实现了真正的异步 IO</strong></li>
<li>Linux 系统异步 IO 在 2.6 版本引入，但其<strong>底层实现还是用多路复用模拟了异步 IO，性能没有优势</strong></li>
</ul>
<p><strong>AIO示例</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.AsynchronousChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.AsynchronousFileChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.CompletionHandler;<br><span class="hljs-keyword">import</span> java.nio.file.Paths;<br><span class="hljs-keyword">import</span> java.nio.file.StandardOpenOption;<br><br><span class="hljs-keyword">import</span> <span class="hljs-keyword">static</span> com.plum.netty.nio.ByteBufferUtil.debugAll;<br><br><span class="hljs-meta">@Slf4j</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AioFileChannel</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        <span class="hljs-keyword">try</span>(AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(<span class="hljs-string">&quot;data.txt&quot;</span>), StandardOpenOption.READ))&#123;<br>            ByteBuffer buffer = ByteBuffer.allocate(<span class="hljs-number">16</span>);<br>            log.debug(<span class="hljs-string">&quot;read begin...&quot;</span>);<br>            channel.read(buffer, <span class="hljs-number">0</span>, buffer, <span class="hljs-keyword">new</span> CompletionHandler&lt;Integer, ByteBuffer&gt;() &#123;<br>                <span class="hljs-meta">@Override</span><br>                <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">completed</span><span class="hljs-params">(Integer result, ByteBuffer attachment)</span> </span>&#123;<br>                    attachment.flip();<br>                    debugAll(attachment);<br>                &#125;<br><br>                <span class="hljs-meta">@Override</span><br>                <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">failed</span><span class="hljs-params">(Throwable exc, ByteBuffer attachment)</span> </span>&#123;<br>                    exc.printStackTrace();<br>                &#125;<br>            &#125;);<br>            log.debug(<span class="hljs-string">&quot;read end...&quot;</span>);<br><br>        &#125;<span class="hljs-keyword">catch</span> (IOException e)&#123;<br>            e.printStackTrace();<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/NIO/" class="category-chain-item">NIO</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/NIO/">#NIO</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>NIO 基础</div>
      <div>https://bolg.plumdong.top/2022/01/15/NIO基础/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>马振东</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年1月15日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/20/Netty/" title="Netty 框架学习">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Netty 框架学习</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/01/Redis%20ZSet%20%E5%BA%95%E5%B1%82%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" title="Redis ZSet 底层数据结构">
                        <span class="hidden-mobile">Redis ZSet 底层数据结构</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
